/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CargaVisita.java
 *
 * Created on Feb 18, 2011, 6:36:26 PM
 */

package forms;

import beans.Boliche;
import beans.Socio;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.RowFilter;
import javax.swing.RowFilter.Entry;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import managers.ManagerVisitas;
import util.VisitasTableModel;

/**
 *
 * @author nMoncho
 */
public class CargaVisita extends javax.swing.JFrame {

    private JRadioButton radioSeleccionado;
    private ManagerVisitas gestor = new ManagerVisitas();
    private Socio socioBuscado;
    
    //Atributos para la lista de links
    private TableRowSorter<VisitasTableModel> sorter;
    private ButtonGroup radiosDiasGroup = new ButtonGroup();
    //Para tabla Zebra like
    private static final Color evenColor = new Color(221, 238, 255);
    //UI para el link
    private LinkViewRadioButtonUI ui = new LinkViewRadioButtonUI();
    private int visitasPorPagina = 25;
    private final int paginasLR = 5;
    private int paginaActual = 0;
    
    /** Creates new form CargaVisita */
    public CargaVisita() {
        initComponents();
        initializeRadioButtons();

        Boliche[] boliches = gestor.getBoliches();
        for(int i=0;i<boliches.length;i++){
            comboBoliche.addItem(boliches[i]);
        }
        
        tableSocios.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        radioLunes.setSelected(true);

        //Listener de cambios de texto en campo de busqueda
        textSocio.getDocument().addDocumentListener(new DocumentListener(){
            @Override public void insertUpdate(DocumentEvent e) {}
            @Override public void changedUpdate(DocumentEvent e) {}
            @Override
            public void removeUpdate(DocumentEvent e) {
                if(CargaVisita.this.textSocio.getText().length() == 0){
                    CargaVisita.this.socioBuscado = null;//Si borro el texto, tambien borro la busqueda
                }
            }
        });

        this.setLocation(200, 200);
        this.sorter = new TableRowSorter<VisitasTableModel>((VisitasTableModel)tableSocios.getModel());
        tableSocios.setRowSorter(sorter);

        panelLinks.setLayout(new BoxLayout(panelLinks, BoxLayout.X_AXIS));

        comboVisitasPorPagina.setSelectedIndex(2);
        comboVisitasPorPagina.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    if(visitasPorPagina != ((Integer)comboVisitasPorPagina.getSelectedItem()).intValue()){
                        visitasPorPagina = ((Integer)comboVisitasPorPagina.getSelectedItem()).intValue();
                        makeLinkBox(0);//Volver al inicio
                    }
                }
            }
        });

        ButtonGroup bg = new ButtonGroup();
        bg.add(radioKubik);
        bg.add(radioNuvvia);
        radioKubik.setSelected(true);
    }

    private void initializeRadioButtons(){
        //Agregar radio button al grupo al grupo
        radiosDiasGroup.add(radioLunes);
        radiosDiasGroup.add(radioMartes);
        radiosDiasGroup.add(radioMiercoles);
        radiosDiasGroup.add(radioJueves);
        radiosDiasGroup.add(radioViernes);
        radiosDiasGroup.add(radioSabado);
        radiosDiasGroup.add(radioDomingo);
        radiosDiasGroup.add(radioFeriado);

        radioLunes.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Lunes");
                }
            }
        });
        radioMartes.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Martes");
                }
            }
        });
        radioMiercoles.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Miercoles");
                }
            }
        });
        radioJueves.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Jueves");
                }
            }
        });
        radioViernes.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Viernes");
                }
            }
        });
        radioSabado.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Sabado");
                }
            }
        });
        radioDomingo.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Domingo");
                }
                    
            }
        });
        radioFeriado.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED && CargaVisita.this.radioSeleccionado != (JRadioButton)e.getSource()){
                    CargaVisita.this.radioSeleccionado = (JRadioButton)e.getSource();
                    CargaVisita.this.recalcularPuntajeEnBaseADia("Feriado");
                }
            }
        });
    }

    /**
     * Este metodo busca el Date mas proximo a la fecha actual en base al nombre dia
     * Luego setea el DateChooser con es fecha
     */
    private void recalcularPuntajeEnBaseADia(String nombreDia){
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        //Recalcular puntajes para todo el modelo
        gestor.actualizarPuntajesParaTodaTabla(nombreDia);
        
        tableSocios.updateUI();
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelBoliche = new javax.swing.JLabel();
        comboBoliche = new javax.swing.JComboBox();
        labelSocio = new javax.swing.JLabel();
        textSocio = new javax.swing.JTextField();
        botonAgregar = new javax.swing.JButton();
        scrollTabla = new javax.swing.JScrollPane();
        tableSocios = new javax.swing.JTable(){//Agrego look zebra
            @Override
            public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
                Component c = super.prepareRenderer(tcr, row, column);
                if(isRowSelected(row)) {
                    c.setForeground(getSelectionForeground());
                    c.setBackground(getSelectionBackground());
                }else{
                    c.setForeground(getForeground());
                    c.setBackground((row%2!=0)?evenColor:getBackground());
                }
                return c;
            }
        }
        ;
        botonCancelar = new javax.swing.JButton();
        botonAceptar = new javax.swing.JButton();
        labelDiaVisita = new javax.swing.JLabel();
        botonBuscar = new javax.swing.JButton();
        radioLunes = new javax.swing.JRadioButton();
        radioMartes = new javax.swing.JRadioButton();
        radioMiercoles = new javax.swing.JRadioButton();
        radioJueves = new javax.swing.JRadioButton();
        radioViernes = new javax.swing.JRadioButton();
        radioSabado = new javax.swing.JRadioButton();
        radioDomingo = new javax.swing.JRadioButton();
        separator1 = new javax.swing.JSeparator();
        radioFeriado = new javax.swing.JRadioButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        botonBorrar = new javax.swing.JButton();
        panelLinks = new javax.swing.JPanel();
        labelCantidad = new javax.swing.JLabel();
        labelVisitasPorPagina = new javax.swing.JLabel();
        comboVisitasPorPagina = new javax.swing.JComboBox();
        labelSocioDe = new javax.swing.JLabel();
        radioKubik = new javax.swing.JRadioButton();
        radioNuvvia = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cargar Visitas");
        setIconImage(new ImageIcon(getClass().getResource("/resources/arrow-branch-bgr-16-ns.png")).getImage());

        labelBoliche.setText("Boliche:");
        labelBoliche.setName("labelBoliche"); // NOI18N

        comboBoliche.setModel(new javax.swing.DefaultComboBoxModel());
        comboBoliche.setToolTipText("Selecciona el boliche");
        comboBoliche.setName("comboBolicha"); // NOI18N
        comboBoliche.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboBolicheActionPerformed(evt);
            }
        });

        labelSocio.setText("Socio:");
        labelSocio.setName("labelSocio"); // NOI18N

        textSocio.setToolTipText("Ingresa el Legajo del Socio");
        textSocio.setName("textSocio"); // NOI18N
        textSocio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textSocioActionPerformed(evt);
            }
        });

        botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/person-plus-16-ns.png"))); // NOI18N
        botonAgregar.setText("Agregar");
        botonAgregar.setToolTipText("Hace click para agregar la visita");
        botonAgregar.setName("botonAgregar"); // NOI18N
        botonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAgregarActionPerformed(evt);
            }
        });

        tableSocios.setIntercellSpacing(new Dimension());
        tableSocios.setModel(gestor.getModel());
        tableSocios.setShowHorizontalLines(false);
        tableSocios.setShowVerticalLines(false);
        tableSocios.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tableSociosKeyPressed(evt);
            }
        });
        scrollTabla.setViewportView(tableSocios);

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/badge-square-cross-16-ns.png"))); // NOI18N
        botonCancelar.setText("Cerrar");
        botonCancelar.setToolTipText("Cerrar la ventana");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        botonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/badge-square-check-16-ns.png"))); // NOI18N
        botonAceptar.setText("Guardar");
        botonAceptar.setToolTipText("Guardar los Cambios");
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAceptarActionPerformed(evt);
            }
        });

        labelDiaVisita.setText("Dia de Visita: ");

        botonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/search-16-ns.png"))); // NOI18N
        botonBuscar.setText("Buscar");
        botonBuscar.setToolTipText("Hace click para buscar por socio");
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBuscarActionPerformed(evt);
            }
        });

        radioLunes.setText("Lunes");

        radioMartes.setText("Martes");

        radioMiercoles.setText("Miercoles");

        radioJueves.setText("Jueves");

        radioViernes.setText("Viernes");

        radioSabado.setText("Sabado");

        radioDomingo.setText("Domingo");

        radioFeriado.setText("Feriado");

        jLabel1.setText("Visitas Cargadas: ");

        botonBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/person-minus-16-ns.png"))); // NOI18N
        botonBorrar.setText("Borrar");
        botonBorrar.setToolTipText("Hace click para borrar una visita");
        botonBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBorrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelLinksLayout = new javax.swing.GroupLayout(panelLinks);
        panelLinks.setLayout(panelLinksLayout);
        panelLinksLayout.setHorizontalGroup(
            panelLinksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 221, Short.MAX_VALUE)
        );
        panelLinksLayout.setVerticalGroup(
            panelLinksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 28, Short.MAX_VALUE)
        );

        labelCantidad.setText("Cant. de Visitas: ");

        labelVisitasPorPagina.setText("Visitas por pagina: ");

        comboVisitasPorPagina.setModel(new javax.swing.DefaultComboBoxModel(new Integer[] { 5, 10, 25, 50 }));

        labelSocioDe.setText("Socio de:");

        radioKubik.setText("Kubik");

        radioNuvvia.setText("Nuvvia");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(labelDiaVisita)
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioLunes)
                    .addComponent(radioViernes))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioSabado)
                    .addComponent(radioMartes))
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioMiercoles)
                    .addComponent(radioDomingo))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioFeriado)
                    .addComponent(radioJueves))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(labelBoliche)
                .addGap(28, 28, 28)
                .addComponent(comboBoliche, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(521, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(labelVisitasPorPagina)
                        .addGap(18, 18, 18)
                        .addComponent(comboVisitasPorPagina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 345, Short.MAX_VALUE)
                        .addComponent(botonAceptar)
                        .addGap(28, 28, 28)
                        .addComponent(botonCancelar)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(scrollTabla, javax.swing.GroupLayout.DEFAULT_SIZE, 692, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(panelLinks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(labelCantidad)
                        .addGap(132, 132, 132))))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(separator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(labelSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(labelSocioDe)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioKubik)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioNuvvia))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(textSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(botonBuscar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(botonAgregar)
                                .addGap(18, 18, 18)
                                .addComponent(botonBorrar)))))
                .addContainerGap(110, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botonAceptar, botonCancelar});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botonAgregar, botonBuscar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelBoliche)
                            .addComponent(comboBoliche, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(17, 17, 17)
                        .addComponent(separator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(labelDiaVisita)
                                    .addComponent(radioLunes)
                                    .addComponent(radioMartes))
                                .addGap(6, 6, 6)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(radioViernes)
                                    .addComponent(radioSabado)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(radioMiercoles)
                                    .addComponent(radioJueves))
                                .addGap(6, 6, 6)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(radioDomingo)
                                    .addComponent(radioFeriado))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelSocio)
                            .addComponent(textSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(botonBuscar)
                            .addComponent(botonAgregar)
                            .addComponent(botonBorrar))
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(17, 17, 17)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelCantidad)
                                    .addComponent(panelLinks, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(scrollTabla, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(botonAceptar)
                                .addComponent(botonCancelar))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(labelVisitasPorPagina)
                                .addComponent(comboVisitasPorPagina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(171, 171, 171)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelSocioDe)
                            .addComponent(radioKubik, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(radioNuvvia, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {botonAceptar, botonCancelar});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void comboBolicheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBolicheActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboBolicheActionPerformed

    private void textSocioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textSocioActionPerformed
        if(socioBuscado!= null)
            agregarVisita();
        else
            buscarSocio();
    }//GEN-LAST:event_textSocioActionPerformed

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        int confirmacion = JOptionPane.showConfirmDialog(this, "¿Estas seguro que deseas cerrar esta ventana?", "Cerrar", JOptionPane.YES_NO_OPTION+JOptionPane.INFORMATION_MESSAGE);
        if(confirmacion == JOptionPane.YES_OPTION){
            this.setVisible(false);
            this.dispose();
        }
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void tableSociosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableSociosKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_DELETE){
            borrarVisita();
        }
    }//GEN-LAST:event_tableSociosKeyPressed

    private void botonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarActionPerformed
        agregarVisita();
    }//GEN-LAST:event_botonAgregarActionPerformed

    private void botonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarActionPerformed
        buscarSocio();
    }//GEN-LAST:event_botonBuscarActionPerformed

    private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        if(tableSocios.isEditing()){
            if(tableSocios.getCellEditor().stopCellEditing())
                gestor.guardarVisitas(radioSeleccionado.getText(), (Boliche)comboBoliche.getSelectedItem());
        }else
            gestor.guardarVisitas(radioSeleccionado.getText(), (Boliche)comboBoliche.getSelectedItem());
        
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }//GEN-LAST:event_botonAceptarActionPerformed

    private void botonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBorrarActionPerformed
        borrarVisita();
    }//GEN-LAST:event_botonBorrarActionPerformed

    private void buscarSocio(){
        this.textSocio.setText(textSocio.getText().trim());
        String text = this.textSocio.getText();

        try{
            int legajoInt = Integer.parseInt(text);
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            Integer idBoliche = null;
            String sBoliche = null;
            if(radioKubik.isSelected())
                sBoliche = "kubik";
            else
                sBoliche = "nuvvia";

            for(int i=0;i<comboBoliche.getItemCount();i++){
                if(((Boliche)comboBoliche.getItemAt(i)).getNombre().equalsIgnoreCase(sBoliche)){
                    idBoliche = ((Boliche)comboBoliche.getItemAt(i)).getId();
                }
            }

            Socio socioBuscado2 = gestor.getSocioPorLegajoYBoliche(text, idBoliche);
            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

            if(socioBuscado2 == null)
                JOptionPane.showMessageDialog(this, "No se encontro el socio con el legajo "+text, "Error al buscar el socio", JOptionPane.ERROR_MESSAGE+JOptionPane.OK_OPTION);
            else{
                this.textSocio.setText(socioBuscado2.getApellido()+", "+socioBuscado2.getNombre());
                socioBuscado = socioBuscado2;
            }
        }catch(NumberFormatException ex){
            JOptionPane.showMessageDialog(this, "Ingresate el legajo del socio incorrectamente", "Error en legajo", JOptionPane.ERROR_MESSAGE+JOptionPane.OK_OPTION);
        }
    }

    private void agregarVisita(){
        boolean exito = gestor.cargarVisita(socioBuscado, radioSeleccionado.getText());
        if(exito){//Si agrego con exito, lo saco del text y del buscado
            socioBuscado = null;
            textSocio.setText("");
            labelCantidad.setText("Cant. de Visitas: "+tableSocios.getModel().getRowCount());
            if(tableSocios.getModel().getRowCount() > visitasPorPagina)
                makeLinkBox(paginaActual);
        }
        tableSocios.updateUI();
    }

    private void borrarVisita(){
        //Preguntar si realmente quiere borrar la fila
        int respuesta = JOptionPane.showConfirmDialog(this, "¿Realmente deseas borrar la/s visita/s de este/os cliente/s?", "Advertencia", JOptionPane.YES_NO_OPTION);
        if(respuesta == JOptionPane.YES_OPTION){
            int[] selectedRows = this.tableSocios.getSelectedRows();
            int row;
            for(int i=selectedRows.length-1; i>-1;i--){
                row = selectedRows[i] + (this.paginaActual * this.visitasPorPagina);
                gestor.borrarVisita(row);
            }
        }
        labelCantidad.setText("Cant. de Visitas: "+tableSocios.getModel().getRowCount());
        if(tableSocios.getModel().getRowCount() > visitasPorPagina)//Si todavia es mayor, seguir mostrando links
            if(tableSocios.getModel().getRowCount() > visitasPorPagina * paginaActual)
                makeLinkBox(paginaActual);
            else
                makeLinkBox(paginaActual-1);
        else{
            makeLinkBox(0);
            panelLinks.removeAll();
            panelLinks.revalidate();
            panelLinks.repaint();
        }
            
        tableSocios.updateUI();
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CargaVisita().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonAgregar;
    private javax.swing.JButton botonBorrar;
    private javax.swing.JButton botonBuscar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JComboBox comboBoliche;
    private javax.swing.JComboBox comboVisitasPorPagina;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel labelBoliche;
    private javax.swing.JLabel labelCantidad;
    private javax.swing.JLabel labelDiaVisita;
    private javax.swing.JLabel labelSocio;
    private javax.swing.JLabel labelSocioDe;
    private javax.swing.JLabel labelVisitasPorPagina;
    private javax.swing.JPanel panelLinks;
    private javax.swing.JRadioButton radioDomingo;
    private javax.swing.JRadioButton radioFeriado;
    private javax.swing.JRadioButton radioJueves;
    private javax.swing.JRadioButton radioKubik;
    private javax.swing.JRadioButton radioLunes;
    private javax.swing.JRadioButton radioMartes;
    private javax.swing.JRadioButton radioMiercoles;
    private javax.swing.JRadioButton radioNuvvia;
    private javax.swing.JRadioButton radioSabado;
    private javax.swing.JRadioButton radioViernes;
    private javax.swing.JScrollPane scrollTabla;
    private javax.swing.JSeparator separator1;
    private javax.swing.JTable tableSocios;
    private javax.swing.JTextField textSocio;
    // End of variables declaration//GEN-END:variables

    private void makeLinkBox(int paginaActual){
        sorter.setRowFilter(makeRowFilter(paginaActual));
        ArrayList<JRadioButton> links = new ArrayList<JRadioButton>();
        int paginaInicio = paginaActual - paginasLR;
        if (paginaInicio < 0) paginaInicio = 0;

        int cantPaginas = (tableSocios.getModel().getRowCount()/visitasPorPagina) +1;
        if(cantPaginas <= 1){//En caso de que haya solo una pagina no mostrar nada
            panelLinks.removeAll();
            panelLinks.revalidate();
            panelLinks.repaint();
            return;
        }

        this.paginaActual = paginaActual;
        int finPagina = paginaActual + paginasLR;
        if (finPagina > cantPaginas) finPagina = cantPaginas;

        if(paginaActual > 0)
            links.add(makeLinkButton(paginaActual-1, "Ant."));
        for(int i= paginaInicio; i<finPagina;i++){
            links.add(makeLinkButton(i));
        }
        if((paginaActual+1) < finPagina)
            links.add(makeLinkButton(paginaActual+1, "Sig."));

        panelLinks.removeAll();
        ButtonGroup bg = new ButtonGroup();
        panelLinks.add(Box.createHorizontalGlue());
        for(JRadioButton r:links) {
            panelLinks.add(r); bg.add(r);
        }
        panelLinks.add(Box.createHorizontalGlue());
        panelLinks.revalidate();
        panelLinks.repaint();
        links.clear();
    }

    /**
     * Filtro por paginas
     * @param pagina pagina que se fitrara
     * @return el objeto RowFilter para filtrar la JTable
     */
    private RowFilter< VisitasTableModel, Integer > makeRowFilter(final int pagina) {
        return new RowFilter< VisitasTableModel, Integer >(){
            @Override
            public boolean include(Entry<? extends VisitasTableModel, ? extends Integer> entry) {
                int ei = entry.getIdentifier();
                return (pagina*visitasPorPagina <= ei && ei < pagina*visitasPorPagina+visitasPorPagina);
            }
        };
    }

    private JRadioButton makeLinkButton(final int linkPagina){
        JRadioButton radio = new JRadioButton(""+(linkPagina+1));
        radio.setForeground(Color.BLUE);
        radio.setUI(ui);
        if(linkPagina == paginaActual) {
            radio.setSelected(true);
            radio.setForeground(Color.BLACK);
        }
        radio.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            makeLinkBox(linkPagina);
          }
        });
        return radio;
    }

    private JRadioButton makeLinkButton(final int linkPagina, String texto){
        JRadioButton radio = new JRadioButton(texto);
        radio.setForeground(Color.BLUE);
        radio.setUI(ui);
        radio.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            makeLinkBox(linkPagina);
          }
        });
        return radio;
    }
}
